﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using kxcxw.Data.Entities;
using kxcxw.Data;
using Telerik.Web.Mvc.UI;
using System.Collections;
using kxcxw.Data.Common;
using KXCXW.Web.CommonClass;
using System.Web.Security;
using System.IO;
using KXCXW.Web.Areas.Admin.Models;
using kxcxw.Business;

namespace KXCXW.Web.Areas.Admin.Controllers
{
    public class DictController : Controller
    {
        private KXCXWDBContext db = new KXCXWDBContext();

        //
        // GET: /Admin/Dict/
        [Authorize(Roles = DataConstants.Admin)]
        public ViewResult Index()
        {
            var sysiteminfos = db.SysItemInfoes;
            return View(sysiteminfos.ToList());
        }

        //
        // GET: /Admin/Dict/Details/5
        [Authorize(Roles = DataConstants.Admin)]
        public ViewResult Details(string id)
        {
            return View(db.SysItemDetials.Where(e => e.ItemDeitalPID == null && e.ItemID == id));
        }

        //
        // GET: /Admin/Dict/Create
        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Admin/Dict/Create

        [HttpPost]
        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult Create(SysItemInfo sysiteminfo)
        {
            if (ModelState.IsValid)
            {
                sysiteminfo.ItemID = Guid.NewGuid().ToString();
                db.SysItemInfoes.Add(sysiteminfo);
                db.SaveChanges();
                SysItemDetial sysitemdetial = new SysItemDetial();
                sysitemdetial.CreateDate = DateTime.Now;
                sysitemdetial.ItemDeitalID = Guid.NewGuid().ToString();
                sysitemdetial.ItemDeitalPID = null;
                sysitemdetial.ItemID = sysiteminfo.ItemID;
                sysitemdetial.itemDetialName = "请添加类别，该类别为系统默认添加，请右键修改类别名称";
                db.SysItemDetials.Add(sysitemdetial);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return RedirectToAction("Index");
        }

        //
        // GET: /Admin/Dict/Edit/5
        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult Edit(string id)
        {
            SysItemInfo sysiteminfo = db.SysItemInfoes.Find(id);

            return View(sysiteminfo);
        }

        //
        // POST: /Admin/Dict/Edit/5

        [HttpPost]
        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult Edit(SysItemInfo sysiteminfo)
        {
            if (ModelState.IsValid)
            {
                db.Entry(sysiteminfo).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(sysiteminfo);
        }

        //
        // GET: /Admin/Dict/Delete/5
        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult Delete(string id)
        {
            SysItemInfo sysiteminfo = db.SysItemInfoes.Find(id);
            db.SysItemInfoes.Remove(sysiteminfo);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //
        // POST: /Admin/Dict/Delete/5
        [Authorize(Roles = DataConstants.Admin)]
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            SysItemDetial sysitemdetial = db.SysItemDetials.Find(id);
            db.SysItemDetials.Remove(sysitemdetial);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        [Authorize(Roles = DataConstants.Admin)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult _AjaxLoading(TreeViewItem node)
        {


            string parentId = !string.IsNullOrEmpty(node.Value) ? node.Value : null;

            IEnumerable nodes = from item in db.SysItemDetials
                                where item.ItemDeitalPID == parentId
                                orderby item.OrderID
                                select new TreeViewItem
                                {
                                    Text = item.itemDetialName,
                                    Value = item.ItemDeitalID,
                                    LoadOnDemand = item.SysItemDetial1.Count > 0,
                                    Enabled = true
                                };

            return new JsonResult { Data = nodes };
        }
        [Authorize(Roles = DataConstants.Admin)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditNode(int level, string id, string text)
        {

            var category = db.SysItemDetials.FirstOrDefault(c => c.ItemDeitalID == id);
            if (category != null)
            {
                category.itemDetialName = text;
            }
            db.Entry(category).State = EntityState.Modified;
            db.SaveChanges();
            return new EmptyResult();
        }

        [Authorize(Roles = DataConstants.Admin)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteNode(int level, string id)
        {


            var category = db.SysItemDetials.FirstOrDefault(c => c.ItemDeitalID == id);
            if (category != null)
            {
                category.SysItemDetial1.Clear();
                List<string> dictId = new List<string>();
                foreach (var item in category.SysItemDetial1)
                {
                    dictId.Add(item.ItemDeitalID);
                }
                foreach (var item in dictId)
                {
                    DeleteDictItem(item);
                }
                db.SysItemDetials.Remove(category);
                db.SaveChanges();

            }

            return new EmptyResult();
        }
        [Authorize(Roles = DataConstants.Admin)]
        public void DeleteDictItem(string dictId)
        {
            db.SysItemDetials.Remove(db.SysItemDetials.Find(dictId));

        }


        //
        // GET: /Dict/Create
        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult CreateDictDetial(string id)
        {

            ViewData["dictName"] = db.SysItemDetials.Where(q => q.ItemDeitalID == id).FirstOrDefault().itemDetialName;
            ViewData["dictId"] = db.SysItemDetials.Where(q => q.ItemDeitalID == id).FirstOrDefault().ItemDeitalID;
            return View();
        }
        [Authorize(Roles = DataConstants.Admin)]
        [HttpPost]
        public ActionResult CreateDictDetial(SysItemDetial sysitemdetial)
        {
            if (ModelState.IsValid)
            {
                string dictId = Request.Form["hidDictId"];
                SysItemDetial oldsysitemdetial = db.SysItemDetials.Find(dictId);
                sysitemdetial.ItemID = oldsysitemdetial.ItemID;
                sysitemdetial.ItemDeitalID = Guid.NewGuid().ToString();
                sysitemdetial.CreateDate = DateTime.Now;
                string type = Request.Form["rbtnDictId"];
                if (type == "0")
                {
                    sysitemdetial.ItemDeitalPID = oldsysitemdetial.ItemDeitalPID;
                }
                else
                {
                    sysitemdetial.ItemDeitalPID = oldsysitemdetial.ItemDeitalID;
                }

                db.SysItemDetials.Add(sysitemdetial);
                db.SaveChanges();
                return RedirectToAction("Details/" + oldsysitemdetial.ItemID);
            }
            return RedirectToAction("Index");
        }

        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult CategoryList()
        {
            List<SysItemDetial> rootlist = (from q in db.SysItemDetials
                                            where q.ItemDeitalPID == null && q.ItemID == DataConstants.ProductTypeItemID
                                            orderby q.OrderID
                                            select q).ToList();
            foreach (SysItemDetial item in rootlist)
            {
                ViewData[item.ItemDeitalID] = (from q in db.SysItemDetials
                                               where q.ItemDeitalPID == item.ItemDeitalID
                                               orderby q.OrderID
                                               select q).ToList<SysItemDetial>();
            }
            return View(rootlist);
        }

        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult WebSiteList()
        {
            List<SysItemDetial> rootlist = (from q in db.SysItemDetials
                                            where q.ItemDeitalPID == null && q.ItemID == DataConstants.SourceTypeItemID && q.ItemDeitalID != "A445196E-75DE-4FF5-84F4-74176C629E9A"
                                            orderby q.OrderID
                                            select q).ToList();
            return View(rootlist);
        }

        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult CategoryEdit(string id)
        {
            ViewBag.UserKey = Membership.GetUser().ProviderUserKey.ToString();
            SysItemDetial info = db.SysItemDetials.Find(id);

            return View(info);
        }

        [HttpPost]
        [Authorize(Roles = DataConstants.Admin)]
        public ActionResult CategoryEdit(SysItemDetial info)
        {
            if (ModelState.IsValid)
            {
                HttpPostedFileBase file = Request.Files["ImageName"];
                string fileName = "";
                try
                {
                    if (file != null && file.FileName != "")
                    {
                        fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                        if (ImgUpLoadHelper.SavePicFormat(Server.MapPath("~/Content/upload/SiteLogo/"), fileName, 100, 40, file) != "")
                        {
                            db.Entry(info).Entity.ImgInfo = fileName;
                        }
                        else
                        {
                            ModelState.AddModelError("file", "图片上传失败！");
                        }
                    }

                    db.Entry(info).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("WebSiteList");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("exception", "出现异常！");
                }
                return RedirectToAction("CategoryList");
            }

            return View(info);
        }


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }//class
}